package cn.iocoder.yudao.module.aiposter.remote;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.module.aiposter.config.PosterConfig;
import cn.iocoder.yudao.module.aiposter.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.aiposter.utils.CommonUtils;
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.LoadState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class DrawClient {
    private final PosterConfig posterConfig;

    public DrawClient(PosterConfig posterConfig) {
        this.posterConfig = posterConfig;
    }

    /**
     * 封面截图
     *
     * @param posterId 海报ID
     * @return 截图存储路径
     */
    public Path coverScreenshot(Long posterId) {
        String url = posterConfig.getDrawUrl() + "?id=" + posterId + "&isCover=true";
        return screenshot(url, -1, -1);
    }

    /**
     * 封面截图
     *
     * @param posterId 海报ID
     * @return 截图存储路径
     */
    public Path posterScreenshot(Long posterId, Integer width, Integer height) {
        String url = posterConfig.getDrawUrl() + "?id=" + posterId;
        return screenshot(url, width, height);
    }

    /**
     * 海报截图
     *
     * @param url 绘画地址
     * @return 截图存储路径
     */
    public Path screenshot(String url, Integer width, Integer height) {
        try (Playwright playwright = Playwright.create()) {
            BrowserType browserType = playwright.chromium();
            try (Browser browser = browserType.launch()) {
                BrowserContext context = browser.newContext();
                context.setDefaultTimeout(60000);
                Page page = context.newPage();
                File localTmpSaveDir = new File(posterConfig.getLocalUploadDir());
                if (!localTmpSaveDir.exists() && !localTmpSaveDir.isDirectory()) {
                    localTmpSaveDir.mkdirs();
                }
                Path savePath = Paths.get(posterConfig.getLocalUploadDir(), "screenshot-" + browserType.name() + "_" + CommonUtils.generateShortUuid() + ".png");
                page.navigate(url);
                // 默认超时60秒
                page.setDefaultTimeout(60000);
                page.setDefaultNavigationTimeout(60000);
                // 前端配合设置元素
                page.waitForFunction("() => document.getElementById('finishLoad') != null");
                if (width > 0 && height > 0) {
                    // 指定大小渲染完整海报
                    page.setViewportSize(width, height);
                }
                page.locator("#page-design-canvas")
                        .screenshot(new Locator.ScreenshotOptions().setPath(savePath));
                return savePath;
            } catch (PlaywrightException e) {
                e.printStackTrace();
                throw new ServiceException(ErrorCodeConstants.POSTER_DRAW_CLIENT_ERROR);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException(ErrorCodeConstants.POSTER_SCREENSHOT_ERROR);
            }
        } catch (ServiceException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(ErrorCodeConstants.POSTER_DRAW_BROWSER_ERROR);
        }
    }
}
